package com.lfg.leetcode.leetcode100;


public class No132minCut {

    public static int minCut(String s) {
        if (null == s) {
            return 0;
        }
        int length = s.length();
        if (length == 1) {
            return 0;
        }
        boolean[][] palindrome = new boolean[length][length];
        for (int i = length - 1; i >= 0; i--) {
            for (int j = i; j < length; j++) {
                if (j == i || (s.charAt(i) == s.charAt(j) && (j - i <= 2 || palindrome[i + 1][j - 1]))) {
                    palindrome[i][j] = true;
                }
            }
        }
        int[] result = new int[length];
        for (int i = 0; i < length; i++) {
            result[i] = length - 1;
        }
        result[0] = 0;
        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j < length; j++) {
                if (palindrome[i][j]) {
                    int b = result[i];
                    if (i > 0) {
                        b = result[i - 1] + 1;
                    }
                    result[j] = Math.min(result[j], b);
                } else {
                    result[j] = Math.min(result[j], result[j - 1] + 1);
                }
            }
        }
        return result[length - 1];
    }
}
